import { Injectable } from '@nestjs/common';
import { CreateBookmarkDto } from './dto/create-bookmark.dto';
import { InjectRepository } from '@nestjs/typeorm';
import { Bookmark } from './entities/bookmark.entity';
import { Repository } from 'typeorm';
import { PageQuery } from '../../../util/entity/page.entity';
import { buildQuery } from '../../../util/common-fn';
import { UpdateBookmarkDto } from './dto/update-bookmark.dto';

@Injectable()
export class BookmarkService {
  constructor(
    @InjectRepository(Bookmark)
    private bookmarkRepository: Repository<Bookmark>,
  ) {}
  async create(createBookmarkDto: CreateBookmarkDto, userId: number) {
    const bookmark = await this.bookmarkRepository.save(createBookmarkDto);
    await this.bookmarkRepository
      .createQueryBuilder()
      .relation(Bookmark, 'user')
      .of(bookmark.id)
      .set(userId);
    return;
  }

  async findAll(pageQuery: PageQuery<Bookmark>, userId: number) {
    const andWhere = {
      user: {
        id: userId,
      },
    };
    return this.bookmarkRepository.findAndCount(
      buildQuery(pageQuery, andWhere),
    );
  }

  async findOne(id: number, userId: number) {
    return this.bookmarkRepository.findOneByOrFail({
      id,
      user: { id: userId },
    });
  }

  async update(
    id: number,
    updateBookmarkDto: UpdateBookmarkDto,
    userId: number,
  ) {
    return this.bookmarkRepository.update(
      { id, user: { id: userId } },
      updateBookmarkDto,
    );
  }

  async remove(id: number, userId: number) {
    await this.findOne(id, userId);
    return this.bookmarkRepository.softDelete({ id, user: { id: userId } });
  }

  /**
   * 增加次数
   * @param id
   * @param userId
   */
  async addCount(id: number, userId: number) {
    return await this.bookmarkRepository.increment(
      { id, user: { id: userId } },
      'count',
      1,
    );
  }
}
